package com.renwei.yunlong.activity.work;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.event.WorkPageRefreshEvent;
import com.renwei.yunlong.http.Api;
import com.renwei.yunlong.http.HttpPresenter;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.GetTimeUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.view.SimpleOptionView;
import com.renwei.yunlong.wheelview.OnWheelChangedListener;
import com.renwei.yunlong.wheelview.WheelView;
import com.renwei.yunlong.wheelview.adapter.ArrayWheelAdapter;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;


/**
 * 滚动选择日期、时间
 * <p>
 * 去现场、非现场、接受 -- 页面
 * <p>
 * Created by Administrator on 2017/9/11.
 */

public class WorkDateSelecterActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener, OnWheelChangedListener {

    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.tv_complete)
    TextView tvComplete;
    @Bind(R.id.wl_ymd)
    WheelView wl_ymd;
    @Bind(R.id.wl_week)
    WheelView wl_week;
    @Bind(R.id.wl_hour)
    WheelView wl_hour;
    @Bind(R.id.wl_min)
    WheelView wl_min;
    @Bind(R.id.button_determine)
    Button buttonDetermine;
    private String ymdData[] = new String[720];

    private String pager;

    String[] week_str =
            {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    String[] xiaoshi_start =
            {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18",
                    "19", "20", "21", "22", "23"};

    String[] fenzhong_start =
            {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18",
                    "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36",
                    "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54",
                    "55", "56", "57", "58", "59"};
    private long currentTime;
    private String requestId;
    private String eventId;
    private int currentId;

    private String YMD = "";
    private String HOUR = "";
    private String MIN = "";
    private ArrayWheelAdapter<String> weekAdapter;
    private ArrayWheelAdapter<String> hourAdapter;
    private ArrayWheelAdapter<String> minAdapter;

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_date_selecter);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        requestId = getIntent().getStringExtra("requestId");
        eventId = getIntent().getStringExtra("eventId");
        pager = getIntent().getStringExtra("pager");
        initData();
        initView();
    }

    //初始化数据
    private void initData() {
        currentTime = System.currentTimeMillis();
        long day = 24 * 60 * 60 * 1000;
        if ("开始时间".equals(pager) || "结束时间".equals(pager)) {
            long lastYear = currentTime - day * 360;
            for (int i = 0; i < 720; i++) {
                long time = lastYear + day * i;
                if (time == currentTime) {
                    currentId = i;
                }
                ymdData[i] = GetTimeUtils.getYMDTime(time);
            }
        } else {
            for (int i = 0; i < 720; i++) {
                long time = currentTime + day * i;
                ymdData[i] = GetTimeUtils.getYMDTime(time);
            }
        }
        YMD = GetTimeUtils.getYMDTime(currentTime);
    }

    private void initView() {
        if ("接受".equals(pager)) {
            simpleTileView.setTitle("接受");
            TextView titleView = simpleTileView.getTitleView();
            Drawable titleLeft = getResources().getDrawable(R.mipmap.icon_title_help);
            titleLeft.setBounds(0, 0, titleLeft.getMinimumWidth(), titleLeft.getMinimumHeight());
            titleView.setCompoundDrawables(null, null, titleLeft, null);
            titleView.setCompoundDrawablePadding(10);
            titleView.setOnClickListener(this);
            tvComplete.setText("预计开始处理时间");
        } else if ("去现场".equals(pager)) {
            simpleTileView.setTitle("去现场");
            tvComplete.setText("预计到场时间");
        } else if ("非现场".equals(pager)) {
            simpleTileView.setTitle("非现场");
            tvComplete.setText("预计开始处理时间");
        } else if ("到场时间".equals(pager)) {
            simpleTileView.setTitle("到场时间");
            tvComplete.setText("预计到场时间");
        } else if ("开始时间".equals(pager)) {
            simpleTileView.setTitle("开始时间");
            tvComplete.setText("开始时间");
        } else if ("结束时间".equals(pager)) {
            simpleTileView.setTitle("结束时间");
            tvComplete.setText("结束时间");
        }
        buttonDetermine.setOnClickListener(this);

        initWheelView();
    }

    private void initWheelView() {
        ArrayWheelAdapter<String> ymdAdapter = new ArrayWheelAdapter<>(this);
        ymdAdapter.setData(ymdData);
        ymdAdapter.setTextSize(18);
        wl_ymd.setViewAdapter(ymdAdapter);
        wl_ymd.setCurrentItem(currentId);
        wl_ymd.addChangingListener(this);

        weekAdapter = new ArrayWheelAdapter<>(this);
        weekAdapter.setTextSize(18);
        wl_week.setViewAdapter(weekAdapter);
        wl_week.setEnabled(false);

        hourAdapter = new ArrayWheelAdapter<>(this);
        hourAdapter.setTextSize(18);
        wl_hour.setViewAdapter(hourAdapter);
        wl_hour.addChangingListener(this);

        minAdapter = new ArrayWheelAdapter<>(this);
        minAdapter.setTextSize(18);
        wl_min.setViewAdapter(minAdapter);
        wl_min.addChangingListener(this);

        if ("开始时间".equals(pager) || "结束时间".equals(pager)) {
            wl_ymd.setCyclic(true);
            wl_week.setCyclic(true);
            wl_hour.setCyclic(true);// 可循环滚动
            wl_min.setCyclic(true);// 可循环滚动
        } else {
            wl_ymd.setCyclic(false);
            wl_week.setCyclic(false);
            wl_hour.setCyclic(false);// 可循环滚动
            wl_min.setCyclic(false);// 可循环滚动
        }

        Calendar c = Calendar.getInstance();
        int curYear = c.get(Calendar.YEAR);
        int curMonth = c.get(Calendar.MONTH) + 1;//通过Calendar算出的月数要+1
        int curDate = c.get(Calendar.DATE);
        changeWeek(curYear, curMonth, curDate, 0);
        changeHour(0);
        changeMin(0);
    }

    private void confirm() {
        HttpPresenter hp = new HttpPresenter(this);
        hp.setshowDialogcontent("正在加载");
        hp.setUrl(getUrl());
        hp.putParam("jsonBean", getJson());
        hp.setCallBack(this);
        hp.post();
    }

    private String getUrl() {
        String url = "";
        if ("接受".equals(pager)) {
            if ("1".equals(companyType)) {
                url = Api.$().OWNER_JIEDAN_URL;
            } else if ("2".equals(companyType)) {
                url = Api.$().SERVICE_JIEDAN_URL;
            }
        } else if ("去现场".equals(pager) || "非现场".equals(pager)) {
            if ("1".equals(companyType)) {
                url = Api.$().OWNER_XIANCHANG_URL;
            } else if ("2".equals(companyType)) {
                url = Api.$().SERVICE_XIANCHANG_URL;
            }
        } else if ("到场时间".equals(pager)) {
            if ("1".equals(companyType)) {

            } else if ("2".equals(companyType)) {

            }
        }
        return url;
    }

    private String getJson() {
        String processTimes = YMD + " " + HOUR + ":" + MIN;
        HashMap<String, String> map = new HashMap<>();
        if ("接受".equals(pager)) {
            map.put("requestId", requestId);
            map.put("eventId", eventId);
            map.put("processTimes", processTimes);
            if ("1".equals(companyType)) {
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            } else if ("2".equals(companyType)) {
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            }
        } else if ("去现场".equals(pager) || "非现场".equals(pager)) {
            map.put("requestId", requestId);
            map.put("eventId", eventId);
            map.put("processTimes", processTimes);
            if ("去现场".equals(pager)) {
                map.put("treatment", "1");
            } else if ("非现场".equals(pager)) {
                map.put("treatment", "2");
            }
            if ("1".equals(companyType)) {
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            } else if ("2".equals(companyType)) {
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            }
        } else if ("到场时间".equals(pager)) {
            if ("1".equals(companyType)) {

            } else if ("2".equals(companyType)) {

            }
        }
        return JsonMapUtil.mapToJson(map);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.button_determine:
                if ("开始时间".equals(pager) || "结束时间".equals(pager) || "到场时间".equals(pager)) {
                    String processTimes = YMD + " " + HOUR + ":" + MIN;
                    Intent intent = new Intent();
                    intent.putExtra("time", processTimes);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    confirm();
                }
                break;
            case R.id.option_textview_title:
                GuideWebActivity.openActivity(this, Api.$().GUIDE_ACCEPT_WORK_URI);
                break;
            default:
                break;
        }
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        switch (wheel.getId()) {
            case R.id.wl_ymd:
                YMD = ymdData[newValue];
                int year = Integer.parseInt(YMD.substring(0, YMD.indexOf("-")));
                int month = Integer.parseInt(YMD.substring(YMD.indexOf("-") + 1, YMD.lastIndexOf("-")));
                int day = Integer.parseInt(YMD.substring(YMD.lastIndexOf("-") + 1, YMD.length()));

                changeWeek(year, month, day, newValue);
                changeHour(newValue);
                changeMin(newValue);
                break;
            case R.id.wl_hour:
                HOUR = hourAdapter.getData()[newValue];
                break;
            case R.id.wl_min:
                MIN = minAdapter.getData()[newValue];
                break;
            default:
                break;
        }
    }

    private void changeWeek(int year, int month, int day, int newValue) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day);
        int i = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (!("开始时间".equals(pager) || "结束时间".equals(pager)) && newValue == 0) { //当前时间  隐藏后面
            weekAdapter.setData(CommonUtils.getListIntArray(week_str, i).get(1));
            wl_week.setCurrentItem(0);
        } else {
            weekAdapter.setData(week_str);
            wl_week.setCurrentItem(i);
        }
    }

    private void changeHour(int newValue) {
        HOUR = new SimpleDateFormat("HH").format(Calendar.getInstance().getTime());
        List<String> list = Arrays.asList(xiaoshi_start);
        int i = list.indexOf(HOUR);
        if (!("开始时间".equals(pager) || "结束时间".equals(pager)) && newValue == 0) { //当前时间  隐藏后面
            hourAdapter.setData(CommonUtils.getListIntArray(xiaoshi_start, i).get(1));
            wl_hour.setCurrentItem(0);
        } else {
            hourAdapter.setData(xiaoshi_start);
            wl_hour.setCurrentItem(i);
        }
    }

    private void changeMin(int newValue) {
        MIN = new SimpleDateFormat("mm").format(Calendar.getInstance().getTime());
        List<String> list = Arrays.asList(fenzhong_start);
        int i = list.indexOf(MIN);
        if (!("开始时间".equals(pager) || "结束时间".equals(pager)) && newValue == 0) { //当前时间  隐藏后面
            minAdapter.setData(CommonUtils.getListIntArray(fenzhong_start, i).get(1));
            wl_min.setCurrentItem(0);
        } else {
            minAdapter.setData(fenzhong_start);
            wl_min.setCurrentItem(i);
        }
    }

    @Override
    public void onSuccess(int requestId, String result) {
        EventBus.getDefault().post(new WorkPageRefreshEvent());
        CommonBean bean = new Gson().fromJson(result, CommonBean.class);
        if (bean.getMessage().getCode() == 200) {
            finish();
            showCenterSuccessMsg(bean.getMessage().getMessage());
        } else {
            showCenterInfoMsg(bean.getMessage().getMessage());
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }

    public static void OpenActivity(Context context, String requestId, String eventId, String pager) {
        Intent i = new Intent(context, WorkDateSelecterActivity.class);
        i.putExtra("requestId", requestId);
        i.putExtra("pager", pager);
        i.putExtra("eventId", eventId);
        context.startActivity(i);
    }

    public static void OpenActivityForResult(Object context, String requestId, String eventId, String pager, int result) {
        if (context instanceof Context) {
            Intent i = new Intent((Context) context, WorkDateSelecterActivity.class);
            i.putExtra("requestId", requestId);
            i.putExtra("pager", pager);
            i.putExtra("eventId", eventId);
            ((Activity) context).startActivityForResult(i, result);
        } else if (context instanceof Fragment) {
            Intent i = new Intent(((Fragment) context).getContext(), WorkDateSelecterActivity.class);
            i.putExtra("requestId", requestId);
            i.putExtra("pager", pager);
            i.putExtra("eventId", eventId);
            ((Fragment) context).startActivityForResult(i, result);
        }
    }

}
